<template>
  <div class="dashboard-container" style="padding: 20px">
    <ToolBar>
      <template #before>
        共1610条件记录
      </template>
      <template #after>
        <el-button size="mini" type="primary" @click="$router.push('/import?type=user')">导入</el-button>
        <el-button type="danger" size="mini" @click="exportExcel">导出</el-button>
        <el-button type="warning" size="mini" @click="showDialog=true">新增员工</el-button>
      </template>
    </ToolBar>
    <el-table :border="true" :data="list" sort="">
      <el-table-column width="100px" label="序号" type="index" sortable />
      <el-table-column label="姓名" prop="username" />
      <el-table-column label="工号" prop="workNumber" />
      <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatData" />
      <el-table-column label="部门名称" prop="departmentName" />
      <el-table-column label="入职时间" prop="timeOfEntry">
        <template v-slot="{row}">
          {{ row.timeOfEntry | formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="账户状态" prop="enableState" align="center">
        <template v-slot="{row}">
          <el-switch :value="row.enableState === 1" />
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="400px">
        <template v-slot="{row}">
          <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
          <el-button type="text" size="small">转正</el-button>
          <el-button type="text" size="small">调岗</el-button>
          <el-button type="text" size="small">离职</el-button>
          <el-button type="text" size="small">角色</el-button>
          <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row type="flex" justify="center" style="margin-top: 20px;">
      <el-pagination
        size="small"
        :background="true"
        :total.sync="page.total"
        :page-size="page.size"
        :current-page.sync="page.page"
        @current-change="handleGetList"
      />
    </el-row>

    <AddEmployee :show-dialog="showDialog" />

    <el-dialog title="头像预览" :visible.sync="showQrcode">
      <el-row type="flex" justify="center">
        <canvas ref="qrCodeRef" />
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import ToolBar from '@/views/employees/components/ToolBar'
import AddEmployee from '@/views/employees/components/AddEmployee'
import { delEmployee, getEmployeeList } from '@/api/employees'
import type from '@/api/constant/employees'
import EmployeeEnum from '@/api/constant/employees'
import { formatDate } from '@/filters'
import defaultImg from '@/assets/common/head.jpg'

export default {
  components: {
    ToolBar,
    AddEmployee
  },
  data() {
    return {
      showQrcode: false,
      defaultImg,
      list: [],
      showDialog: false,
      page: {
        page: 1,
        size: 10,
        total: 0
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {

    async exportExcel() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendors/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.fromJson(headers, rows)
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          // data: [['张三', '13888888888', '2020-10-01', '1', '2020-10-01', '12', '教研部']],
          data,
          filename: '员工表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    async delEmployee(id) {
      try {
        await this.$confirm('是否确定删除当前员工')
        await delEmployee(id)
        this.$message.success('删除成功')
        await this.getList()
      } catch (e) {
        this.$message.error('删除失败~~')
      }
    },
    fromJson(headers, rows) {
      // rows的结构 ->
      // rows: [{username: '234234', mobile: '1398888888', 'workNumber': 123123}, ....]
      // headers的结构 ['姓名', '手机号', '入职日期', ....] -> 配置项里面生效的数据结构
      // rows的预期结果 -> result数组的每一项要和和headers一一对应
      // result -> [['张三', '138888888', '2020-10-01', ...], ['张三', '138888888', '2020-10-01', ...]]
      return rows.map(item => {
        // item 为对象 ->
        // 替换成数组即可 ->
        // 数组的结构要和headers对应起来 ->
        return Object.keys(headers).map(key => {
          // key -> 中文的key
          // 预期 -> 返回当前项的值
          // 值在哪？-> item为真实的数据对象 -> 取到正确的值返回即可

          // 返回值的思路
          // 1. 数据里面的key是中文还是英文？ -> 英文
          // 2. headers里面取到中文key对应的英文key
          // 3. 直接去数据对象里面取数据
          // return item[headers[key]]
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // 格式化日期
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    formatData(row, column, cellValue, index) {
      return type.hireType.find(item => item.id === cellValue)?.value || '未知'
    },
    handleGetList(page) {
      console.log(page)
      this.page.page = page
      this.getList()
    },
    async getList() {
      const { total, rows } = await getEmployeeList(this.page)
      console.log(rows)
      this.list = rows
      this.page.total = total
    }
  }
}
</script>

<style scoped>
.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  cursor: pointer;
}
</style>
